﻿using Domain.Entity;
using DtoFw;
using DtoFw.Query;
using Repository;
using Service.Base;
using System;
using System.Collections.Generic;
using System.Text;
using Util;
using Microsoft.International.Converters.PinYinConverter;
using Cache;

namespace Service
{
    public class MainDicService
    {
        private readonly MainDicRepository _mainDicRepository;
        public MainDicService(MainDicRepository mainDicRepository)
        {
            this._mainDicRepository = mainDicRepository;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public BaseResult Post(DicAddDto dto)
        {
            if (!string.IsNullOrWhiteSpace(dto.Code) && !dto.ChildNode)
            {
                if (_mainDicRepository.Count(new BaseQuery(), t => t.Where(m => m.Code == dto.Code && !m.ChildNode)) > 0)
                    return BaseResult.Failure("非叶子节点不能有相同的字典编号");
            }
            if (!string.IsNullOrWhiteSpace(dto.Name))
            {
                if (_mainDicRepository.Count(new BaseQuery(), t => t.Where(m => m.ParentId == dto.ParentId && m.Name == dto.Name)) > 0)
                    return BaseResult.Failure("叶子节点下不能有重复的字典名");
            }
            if (!string.IsNullOrWhiteSpace(dto.Code) && dto.ChildNode)
            {
                if (_mainDicRepository.Count(new BaseQuery(), t => t.Where(m => m.ParentId == dto.ParentId && m.Code == dto.Code)) > 0)
                    return BaseResult.Failure("叶子节点下不能有重复的字典编号");
            }
            var entity = AutoMapperExtension.MapTo<DicAddDto, MainDicEntity>(dto);
            entity.Creator = dto.UserName;
            entity.CreatorId = dto.UserId;
            entity.Symbol = PinYinConverter.GetPinYin(dto.Name);
            if (_mainDicRepository.Insert(entity) > 0)
            {
                GlobalData.Cache.Remove(CacheKey.Dic_ModuleDictionary);
                return BaseResult.Succeed();
            }
            return BaseResult
                .Failure("新增字典失败");
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public BaseResult Put(DicUpdateDto dto)
        {
            if (!string.IsNullOrWhiteSpace(dto.Code))
            {
                var count = _mainDicRepository.Count(new BaseQuery(), t => t.Where(m => m.Code == dto.Code && !m.ChildNode && m.ParentId != dto.ParentId));
                if (count > 0)
                {
                    return BaseResult.Failure("非叶子节点不能有相同code");
                }
            }
            var entity = _mainDicRepository.Get(new BaseQuery() { Id = dto.Id });
            if (entity == null)
            {
                return BaseResult.Failure("未获取到更新对象");
            }
            entity = AutoMapperExtension.MapTo<DicUpdateDto, MainDicEntity>(dto, entity);
            entity.Modifyer = dto.UserName;
            entity.ModifyerId = dto.UserId;
            entity.Symbol = PinYinConverter.GetPinYin(dto.UserName);
            if (_mainDicRepository.Save(entity).Id > 0)
            {
                GlobalData.Cache.Remove(CacheKey.Dic_ModuleDictionary);
                return BaseResult.Succeed();
            }
            return BaseResult.Failure("新增字典失败");
        }
        /// <summary>
        /// 根据父节点查询
        /// </summary>
        /// <returns></returns>
        public BaseGenericResult<List<DicDto>> QueryToParentId(long? parentId)
        {
            var list = _mainDicRepository.Query(new BaseQuery(),
                  t => t.Where(m => m.ParentId == parentId)).OrderBy(v=>v.Code)?.ToList();
            return MappingList(list);
        }
        /// <summary>
        /// 获取所有字典数据
        /// </summary>
        /// <returns></returns>
        public BaseGenericResult<List<DicDto>> Query()
        {
            var list = _mainDicRepository.Query(new BaseQuery()).OrderBy(v=>v.Code)?.ToList();
            return MappingList(list);
        }
        /// <summary>
        /// 获取所有父字典
        /// </summary>
        /// <returns></returns>
        public BaseGenericResult<Pager<DicDto>> QueryParentDic(DicQueryDto dicQuery)
        {
            BaseGenericResult<Pager<DicDto>> baseResult = new BaseGenericResult<Pager<DicDto>>();
            baseResult.Data = new Pager<DicDto>();
            Pager<MainDicEntity> pager = _mainDicRepository.GetPagerList(dicQuery);
            baseResult.Data.TotalCount = pager.TotalCount;
            baseResult.Data.Data = Util.AutoMapperExtension.MapTo<MainDicEntity, DicDto>(pager.Data);
            return baseResult;
        }
        /// <summary>
        /// 根据父节点查询
        /// </summary>
        /// <returns></returns>
        public BaseGenericResult<List<DicDto>> QueryToParentCode(string parentCode)
        {
            var parentId = _mainDicRepository.Get(new BaseQuery(),
                  t => t.Where(m => m.ParentId == 0 && m.Code == parentCode))?.Id;
            return QueryToParentId(parentId);
        }
        private BaseGenericResult<List<DicDto>> MappingList(List<MainDicEntity> list)
        {
            var mappingList = AutoMapperExtension.MapTo<MainDicEntity, DicDto>(list);
            return BaseGenericResult<List<DicDto>>.Succeed(mappingList);
        }
        /// <summary>
        /// 获取单个字典数据
        /// </summary>
        /// <returns></returns>
        public BaseGenericResult<DicDto> Get(long Id)
        {
            var entity = _mainDicRepository.Get(new BaseQuery() { Id = Id });
            var model = AutoMapperExtension.MapTo<MainDicEntity, DicDto>(entity);
            return BaseGenericResult<DicDto>.Succeed(model);
        }
        /// <summary>
        /// 删除字典
        /// </summary>
        /// <returns></returns>
        public BaseResult Delete(DeleteSingleDto query)
        {
            if (query.Id < 1)
                return BaseResult.Failure("参数异常");
            var entity = _mainDicRepository.Get(new BaseQuery(),
                  t => t.Where(m => m.Id == query.Id));
            var list = _mainDicRepository.Query(new BaseQuery(),
                t => t.Where(m => m.ParentId == entity.Id))?.ToList();
            if (entity.ChildNode || list.Count < 1)
            {
                if (_mainDicRepository.Delete(new Domain.Base.BaseOperate()
                {
                    Id = query.Id,
                    Modifyer = query.UserName,
                    ModifyerId = query.UserId
                }) > 0)
                    return BaseResult.Succeed();
                return BaseResult.Failure("删除失败");
            }
            return BaseResult.Failure("只能删除叶子节点或空的父节点");
        }
    }
}
